package com.sq.partner.manager.service.impl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.sq.partner.manager.common.ActirationErrorInfo;
import com.sq.partner.manager.common.Constants;
import com.sq.partner.manager.dao.ActirationCardApplyDao;
import com.sq.partner.manager.dao.ActivationCardSheetDao;
import com.sq.partner.manager.dao.ArtirationCardDao;
import com.sq.partner.manager.mybatis.model.ActirationApplyCardExcel;
import com.sq.partner.manager.mybatis.model.ActirationCardApply;
import com.sq.partner.manager.mybatis.model.ActirationCardDifinition;
import com.sq.partner.manager.mybatis.model.ActirationCardResultDto;
import com.sq.partner.manager.mybatis.model.ActivationCardSheet;
import com.sq.partner.manager.mybatis.model.GatewayUser;
import com.sq.partner.manager.service.ActirationCardApplyService;
import com.sq.partner.manager.service.ActirationCardPowerService;
import com.sq.partner.manager.util.Page;
import com.sq.partner.manager.util.StrUtil;
/**
 * 卡单申请service实现
 * SQ
 *
 */
@Service
public class ActirationCardApplyServiceImpl implements ActirationCardApplyService{
	@Resource
	private ActirationCardApplyDao actirationCardApplyDao;
	@Resource
	private ActivationCardSheetDao activationCardSheetDao;
	@Resource
	private ArtirationCardDao artirationCardDao;
	@Resource
	private ActirationCardPowerService powerService;
	
	@Override
	public boolean addApplyInfo(ActirationCardApply applyinfo,GatewayUser gatewayuser) throws Exception{
		applyinfo.setStatus(Constants.ACTIR_CARD_APPLY_SQ);
		applyinfo.setAppDate(new Date());
		applyinfo.setAppUserid(gatewayuser.getUserCode());
		applyinfo.setAppDeptno(gatewayuser.getUserComcode());
		return actirationCardApplyDao.insert(applyinfo);
	}
	@Override
	public boolean deleteApplyInfo(String applyid) throws Exception{
		return actirationCardApplyDao.delete(applyid);
	}
	@Override
	public ActirationCardResultDto auditApplyInfo(GatewayUser user,String auditType,String applyid,String yn,String message) throws Exception{
		//返回dto 内有flag （成功标识：true false 字符串） message 错误信息 字符串
		ActirationCardResultDto resultDto=new ActirationCardResultDto();
		ActirationCardApply actirationcardapply=actirationCardApplyDao.query(applyid);
		//是否更新标识  为true才更新
		resultDto.setSuccess(false);
		//复核,验证状态为申请的
		if("0".equals(auditType)&&actirationcardapply.getStatus().equals(Constants.ACTIR_CARD_APPLY_SQ)){
			//校验操作人权限
			if(StrUtil.isNotEmpty(user.getUserPower())&&powerService.checkPower(user.getUserPower(), Constants.ACTIR_CARD_POWER_REVIEW)){
				//复核与申请人不能为同一人校验
				if(user.getUserCode().equals(actirationcardapply.getAppUserid())){
					resultDto.setMessage(ActirationErrorInfo.APPLY_8);
				}
				else{
					//不通过
					if("0".equals(yn)){
						actirationcardapply=putcheckInfo(actirationcardapply, user.getUserCode(), message, Constants.ACTIR_CARD_APPLY_FN);
					}
					//通过
					else if("1".equals(yn)){
						actirationcardapply=putcheckInfo(actirationcardapply, user.getUserCode(), message, Constants.ACTIR_CARD_APPLY_FY);
					}
					resultDto.setSuccess(true);
				}
			}else{
				resultDto.setMessage(ActirationErrorInfo.USER_10);
			}
			
		}
		//核准下发,校验状态为复核通过
		else if("1".equals(auditType)&&actirationcardapply.getStatus().equals(Constants.ACTIR_CARD_APPLY_FY)){
			//校验权限
			if(StrUtil.isNotEmpty(user.getUserPower())&&powerService.checkPower(user.getUserPower(), Constants.ACTIR_CARD_POWER_APPROVAL)){
				//校验不能为同一个人
				if(user.getUserCode().equals(actirationcardapply.getCheckUserid())){
					resultDto.setMessage(ActirationErrorInfo.APPLY_9);
				}
				else{
					//不通过
					if("0".equals(yn)){
						actirationcardapply=putapprovalInfo(actirationcardapply, user, message, Constants.ACTIR_CARD_APPLY_HN);
						resultDto.setSuccess(true);
					}
					//通过
					else if("1".equals(yn)){
						actirationcardapply=putapprovalInfo(actirationcardapply, user, message, Constants.ACTIR_CARD_APPLY_HY);
						//插入下发的激活卡信息
						resultDto=generatingActivationCard(actirationcardapply, user);
						//插入成功后更新申请信息起止号
						if(resultDto.isSuccess()){
							actirationcardapply.setCardnoBegin(resultDto.getStartNo());
							actirationcardapply.setCardnoEnd(resultDto.getEndNo());
						}
					}
				}
			}else{
				resultDto.setMessage(ActirationErrorInfo.USER_10);
			}
		}
		else{
			resultDto.setMessage(ActirationErrorInfo.APPLY_10);
		}
		//是否成功
		if(resultDto.isSuccess()){
			//更新申请信息
			if(!actirationCardApplyDao.update(actirationcardapply)){
				//如果更新失败编辑错误信息
				resultDto.setSuccess(false);
				if(StrUtil.isNotEmpty(resultDto.getStartNo())&&StrUtil.isNotEmpty(resultDto.getEndNo())){
					resultDto.setMessage(ActirationErrorInfo.APPLY_11);
				}else{
					resultDto.setMessage(ActirationErrorInfo.APPLY_12);
				}
			}
			
		}
		return resultDto;
		
	}
	/**
	 * 放入复核信息
	 * @param actirationcardapply
	 * @param checkUserid
	 * @param message
	 * @param status
	 * @return
	 */
	private ActirationCardApply putcheckInfo(ActirationCardApply actirationcardapply,String checkUserid,String message,String status){
		//复核用户id
		actirationcardapply.setCheckUserid(checkUserid);
		//复核用户说明
		actirationcardapply.setCheckMemo(message);
		//复核状态
		actirationcardapply.setStatus(status);
		return actirationcardapply;
	}
	private ActirationCardApply putapprovalInfo(ActirationCardApply actirationcardapply,GatewayUser user,String message,String status){
		//机构号
		actirationcardapply.setUnwriteDeptno(user.getUserComcode());
		//用户id
		actirationcardapply.setUnwriteUserid(user.getUserCode());
		//时间
		actirationcardapply.setUnwriteDate(new Date());
		//说明
		actirationcardapply.setUnwriteMemo(message);
		//状态
		actirationcardapply.setStatus(status);
		return actirationcardapply;
	}
	/**
	 * 根据申请记录批量插入激活卡信息
	 * @param applyid
	 * @param user
	 * @return
	 */
	private ActirationCardResultDto generatingActivationCard(ActirationCardApply applayinfo,GatewayUser user) throws Exception{
		//返回dto 内有flag 成功标识（true,false）字符串 和开始卡号startNo结束卡号endNo
		ActirationCardResultDto resultDto=new ActirationCardResultDto();
		//查询卡模板信息
		ActirationCardDifinition carddifin=new ActirationCardDifinition();
		carddifin.setId(applayinfo.getCardDefineId());
		carddifin=artirationCardDao.query(carddifin);
		ActivationCardSheet info=new ActivationCardSheet();
		info.setCardDefineId(applayinfo.getCardDefineId());
		String headNo=cardNumberRule(applayinfo.getAppDeptno().substring(0, 2),applayinfo.getCardDefineId());
		//暂时的
		info.setAgentNo(headNo+"%");
		//取当前模板的最大单号+1
		String no=activationCardSheetDao.getMaxNo(info);
		Integer maxNo=Integer.valueOf(no.substring(no.length()-6))+1;
		//准备需要插入的数据
		List<ActivationCardSheet> carSheetList=new ArrayList<ActivationCardSheet>();
//		单证类型
		String visacode=null!=carddifin.getcVocherType()?carddifin.getcVocherType():"";
//		失效日期
		Date invalidDate=invalidDate(Integer.valueOf(carddifin.getBenefitTerm()));
//		有价无价 0为有价1为非有价
		String yjflag="0".equals(carddifin.getPricelessType())?"Y":"N";
		for(int i=0;i<applayinfo.getUnitPp();i++){
			//卡单信息
			ActivationCardSheet sheet=new ActivationCardSheet();
			sheet.setCardDefineId(applayinfo.getCardDefineId());
			String cardNo="000000"+(maxNo+i);
			//插入卡号
			String insertNo=headNo+cardNo.substring(cardNo.length()-6);
			sheet.setCardNo(insertNo);
			sheet.setDeptno(applayinfo.getAppDeptno());
			sheet.setStatus(Constants.ACTIR_CARD_STOCK);
			//卡单密码
			sheet.setCardPw(carPasswordRule());
			//卡单申请id
			sheet.setAppId(applayinfo.getAppId());
			//保费
			sheet.setTotPremamt(carddifin.getModalPremamtPp());
			sheet.setDocId(carddifin.getcVocherType());
			//单证类型
			sheet.setDocId(visacode);
			//有价无价‘Y’ —预收‘N’—不预收
			//sheet.setPreFee(yjflag);
			//生成时间
			sheet.setCreatDate(new Date());
			sheet.setOperateDate(new Date());
			//失效日期
			sheet.setDisableDate(invalidDate);
			//获取第一个号
			if(i==0){
				resultDto.setStartNo(insertNo);
			}
			//获取最后一个号
			if(i==applayinfo.getUnitPp()-1){
				resultDto.setEndNo(insertNo);
			}
			carSheetList.add(sheet);
		}
		//插入数据
		if(activationCardSheetDao.insert(carSheetList)){
			resultDto.setSuccess(true);
		}else{
			resultDto.setSuccess(false);
			resultDto.setMessage("插入数据失败");
		}
		return resultDto;
	}
	/**
	 * 生成卡号规则   卡号:当前时间2位年份+2位分公司机构代码+2位月份+4位卡模板号+6位流水号
	 * @param comcode
	 * @return
	 */
	private String cardNumberRule(String comcode,Integer cardefineId){
		SimpleDateFormat sdf=new SimpleDateFormat("yy");
		SimpleDateFormat sdfy=new SimpleDateFormat("MM");
		Date date=new Date();
		String cardid="0000"+cardefineId;
		//卡模板号取4位拼0后截取后4位
		cardid=cardid.substring(cardid.length()-4);
		String no=sdf.format(date)+comcode+sdfy.format(date)+cardid;
		return no;
	}
	/**
	 * 卡密码生成规则  随机生成6位数字
	 * @return
	 */
	private String carPasswordRule(){
		return (int)((Math.random()*9+1)*100000)+"";
	}
	/**
	 * 根据当前时间和有效期限获取失效日期
	 * @param month 期限 单位（月)
	 * @return
	 */
	private Date invalidDate(int month){
		Calendar curr = Calendar.getInstance();
		//增加月份
		curr.add(Calendar.MONTH, month);
		//设置时分秒为0
		curr.set(Calendar.HOUR_OF_DAY, 0);
		curr.set(Calendar.MINUTE, 0);
		curr.set(Calendar.SECOND, 0);
		return curr.getTime();
	}
	@Override
	public ActirationCardApply queryApplyInfo(String applyid) throws Exception{
		return actirationCardApplyDao.query(applyid);
	}
	@Override
	public Page<ActirationCardApply> queryApplyInfoList(Page<ActirationCardApply> page) throws Exception{
		return actirationCardApplyDao.queryPage(page);
	}
	@Override
	public Page<ActirationCardDifinition> queryDefineByRegion(Page<ActirationCardDifinition> page) throws Exception{
		return actirationCardApplyDao.queryDefineByRegion(page);
	}
	@Override
	public List<ActirationApplyCardExcel> queryCardApplyInfo(
			Map<String, Object> map) throws Exception {
		
		return actirationCardApplyDao.queryForCardExcel(map);
	}
	@Override
	public ActirationCardApply getCardInfo(Map<String, Object> map)
			throws Exception {
		
		return actirationCardApplyDao.getCardInfo(map);
	}
	
}
